﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace WinFormTester
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        PerformanceCounter ramCounter;
       Timer tmr = new Timer();

        private void Form1_Load(object sender, EventArgs e)
        {
            ramCounter = new PerformanceCounter("Memory", "Available KBytes");
            //tmr.Elapsed += new ElapsedEventHandler(tmr_Elapsed);
            //tmr.Start();
            tmr.Interval = 1000;
            tmr.Tick += new EventHandler(tmr_Tick);
            tmr.Start();

        }

        void tmr_Tick(object sender, EventArgs e)
        {
            float cpuPercent = (float)getCPUCOunter();

            label1.Text = Math.Round(cpuPercent) + " % CPU";
            label2.Text = getRAMCounter() + " RAM Free";
        }

        
        int totalHits = 0;

        public object getCPUCOunter()
        {

            PerformanceCounter cpuCounter = new PerformanceCounter();
            cpuCounter.CategoryName = "Processor";
            cpuCounter.CounterName = "% Processor Time";
            cpuCounter.InstanceName = "_Total";

            // will always start at 0
            dynamic firstValue = cpuCounter.NextValue();
            System.Threading.Thread.Sleep(1000);
            // now matches task manager reading
            dynamic secondValue = cpuCounter.NextValue();

            return secondValue;

        }


        private void Timer1_Tick(System.Object sender, System.EventArgs e)
        {
            int cpuPercent = (int)getCPUCOunter();
            if (cpuPercent >= 90)
            {
                totalHits = totalHits + 1;
                totalHits = 0;
            }
            else
            {
                totalHits = 0;
            }

            label1.Text = cpuPercent + " % CPU";
            label2.Text = getRAMCounter() + " RAM Free";

        }

        private float getRAMCounter()
        {
            return ramCounter.NextValue();
        }
    }
}
